export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../bin/deps

dir=/data1/tendis
ip=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`

port=51002
echo ${port}
if [[ "AA${port}AA" == "AAAA" ]]; then
        echo "port is empty!!"
        exit
fi

mkdir -p ${dir}/${port}/db
mkdir -p ${dir}/${port}/dump
mkdir -p ${dir}/${port}/log
cp ./tendisplus.conf ${dir}/${port}/

sed -i "s/{{PORT}}/${port}/g" ${dir}/${port}/tendisplus.conf
sed -i "s/{{IP}}/${ip}/g" ${dir}/${port}/tendisplus.conf
sed -i "s:{{DIR}}:${dir}:g" ${dir}/${port}/tendisplus.conf
sed -i "s/{{CLUSTER}}/${CLUSTER}/g" ${dir}/${port}/tendisplus.conf
echo "requirepass ${REDIS_PASSWORD}" >> ${dir}/${port}/tendisplus.conf
echo "masterauth ${REDIS_PASSWORD}" >> ${dir}/${port}/tendisplus.conf
echo "domain-enabled true" >> ${dir}/${port}/tendisplus.conf

cat ${dir}/${port}/tendisplus.conf

../bin/tendisplus ${dir}/${port}/tendisplus.conf


[[ $PAUSE ]] && sleep $PAUSE

#Initialize cluster
SLAVE1_NAME=$(env|grep DEPEND_SERVICE=|awk -F= '{print $2}'|awk -F, '{print $2}'|awk -F: '{print $1}')
SLAVE2_NAME=$(env|grep DEPEND_SERVICE=|awk -F= '{print $2}'|awk -F, '{print $1}'|awk -F: '{print $1}')

../bin/redis-cli -h ${HOSTNAME} -p ${PORT} -a "${REDIS_PASSWORD}" cluster meet ${SLAVE1_NAME}-0  51003
../bin/redis-cli -h ${HOSTNAME} -p ${PORT} -a "${REDIS_PASSWORD}" cluster meet ${SLAVE2_NAME}-0  51004
echo "cluster meet done......"
sleep 10

SIZE=$2

../bin/redis-cli -h ${HOSTNAME} -p ${PORT} -a ${REDIS_PASSWORD}  cluster nodes
for (( i = 0; i < ${SIZE}; i++ )); do
        uuid=$(../bin/redis-cli -h ${HOSTNAME} -p ${PORT} -a ${REDIS_PASSWORD}  cluster nodes |grep ${POD_IP}|awk '{print $1}')
        ../bin/redis-cli -h ${SLAVE1_NAME} -p 51003  -a ${REDIS_PASSWORD} cluster replicate ${uuid}
done
for (( i = 0; i < $((${SIZE} - 1 )); i++ )); do
        ../bin/redis-cli -h ${SLAVE2_NAME} -p 51004 -a ${REDIS_PASSWORD} cluster addslots {$((${i}*${slot_num}))..$((${slot_num}*(${i}+1)-1))}
done
../bin/redis-cli -h ${HOSTNAME}.$((10 + ${SIZE} - 1)) -p ${PORT} -a ${REDIS_PASSWORD} cluster addslots {$(((${SIZE}-1)*${slot_num}))..16383}

echo "cluster build done.."

sleep 5
../bin/redis-cli -h ${HOSTNAME} -p ${PORT}  -a ${REDIS_PASSWORD} cluster nodes